<template>
	<div class="create_shop">		
		<div class="content">			
			<div class="sel_store_type">
				<!--<div class="iconfont back-icon" @click="goBack" v-show="!isWeChat">&#xe624;</div>-->
				<h3>选择宝店类型</h3>
				<div class="type_lists">
					<div class="type-warrp" v-for="item in typeData">
						<div class="type_list" :class="{sel:selIndex===item.id}" @click="selType(item.id)">
							{{ item.name }}						
							<img v-if="selIndex===item.id" class="success" src="../../assets/images/functions/checked.png" alt="" />
						</div>
					</div>
				</div>
			</div>
			<!-- 实体商户 -->
			<div class="store_content1" v-if="selIndex===1">
				<div class="sel_area">
					<x-address title="" value-text-align="left" v-model="address" :list="newAddressData" placeholder="请选择商店所在地"></x-address>
				</div>					
				<div class="store_name">
					<input type="text" @blur="hasStore" placeholder='输入要创建的宝店名称  如“肯德基”' v-model.trim="entityName" />
					<icon v-if="entityName.length>0" type="clear" @click.native="entityName=''" class="clear"></icon>
				</div>
				<div class="store_name">
					<input type="text" placeholder='输入分店名称  如“天安分店” （没有分店可不填）' v-model.trim="branchShop" />
					<icon v-if="branchShop.length>0" type="clear" @click.native="branchShop=''" class="clear"></icon>
				</div>
			</div>
			<!-- 线上电商 -->
			<div class="store_content2" v-if="selIndex===2">
				<div class="store_name" style="margin-bottom:0;">
					<input type="text" placeholder='请粘贴店铺链接（支持淘宝/天猫 ，京东，拼多多）' v-model.trim="onlineLink" />
					<icon v-if="onlineLink.length>0" type="clear" @click.native="onlineLink=''" class="clear"></icon>
				</div>
				<router-link tag="p" to="/viewGetLink" class="links">查看如何获取店铺链接？</router-link>
				<div class="btns">
					<button style="border: none;"></button>
					<button :class="{reds:hasLink}" @click="valiLink">验证链接地址</button>
				</div>
				<div class="info" style="margin-top: 1.3rem;" v-show="onlineInfo.shop_name">
					<div class="avatar" >
						<img :src="onlineInfo.facepath" alt="" width="100%"/>
					</div>
					<p><span class="title">来源</span>:{{onlineInfo.shop_type}}</p>
					<p><span class="title">店铺名称</span>:{{onlineInfo.shop_name}}</p>
				</div>
			</div>
			<!-- 媒体运营 -->
			<div class="store_content3" v-if="selIndex===3"></div>
			<button :class="{reds:disable1}" v-if="selIndex===1" @click="submitEntity">下一步</button>
			<button :class="{reds:disable2}" v-if="selIndex===2" @click="submitOnline">创建</button>
			<button :class="{reds:disable3}" v-if="selIndex===3" @click="">下一步</button>
			<div class="tip" v-show="tipShow">
				<span class="iconfont" style="font-size: .52rem;margin-right: .1rem;">&#xe646;</span>
				{{tipTitle}}
			</div>
		</div>
		<!--  弹出框组件  -->
		<div v-transfer-dom>
	      <x-dialog v-model="dshow" class="dialog-demo">
	        <div class="img-box" style="padding: .4rem;">
	          	<h3 class="title">创建成功</h3>
	          	<x-button @click.native="continueCreate" :mini="true" type="warn">继续创建</x-button>
	          	<x-button @click.native="goHome" :mini="true" type="warn">返回首页</x-button>
	        </div>	        
	        <div @click="dshow=false">
	          <span class="vux-close"></span>
	        </div>
	      </x-dialog>
	    </div>
	</div>
</template>

<script>
	import { Previewer, TransferDom } from 'vux'
	import { setCookie, getCookie, removeCookie, clearCookie } from '@/assets/js/cookie'
	import { getUrlParam } from '@/assets/js/getUrlParam'
	import { XHeader, Tab, TabItem, Icon ,XAddress,XDialog,XButton} from 'vux';
	export default {
		name: 'create_shop',
		data() {
			return {
				dshow          : false,
				isWeChat       : false,
				tipShow        : false,
				tipTitle       : '',
				address        : [],
				typeData: [{
					id: 1,
					name: '实体商户'
				}, {
					id: 2,
					name: '线上电商'
				}, {
					id: 3,
					name: '媒体运营'
				}],
				selIndex: -1,
				entityName : '',  //实体店名称
				onlineLink : '',  //线上电商的店铺链接
				branchShop : '',  //分店名称
				disable1: false,
				disable2: false,
				disable3: false,
				cityList : [],
				hasLink  : false, //有无链接
				onlineInfo : {}
			}
		},
		mounted() {
			this.isWeiXin()
			document.title = '代开宝店';
			this.selIndex = this.typeData[0].id;
			this.getCityList()
		},
		directives: {
		   TransferDom
		},
		methods: {
			//回到首页
			goHome(){
				this.$router.push('/home')
			},
			//继续创建
			continueCreate(){
				this.dshow      = false
				this.disable2   = false
				this.onlineLink = ''
			},
			//选择开什么类型的店
			selType(id) {
				this.selIndex = id;
			},
			//后退一步
			goBack(){
				this.$router.go(-1)
			},
			//判断是不是微信
			isWeiXin(){
				let agent = navigator.userAgent.toLowerCase();
			    if (agent.match(/MicroMessenger/i) == "micromessenger") {
			       	this.isWeChat = true			       	
			    } else {
			        this.isWeChat = false
			    }
			},
			//获取城市列表
			getCityList(){
				let info = {
					userinfo : this.getParams()
				}
				this.$axiosPost('/api/store/citylist',{
					data : JSON.stringify(info)
				}).then( res => {
					if(res && res.code != 404){
						this.cityList = res
					}
					
				})
			},
			//获取参数
			getParams(){
				let userinfo = {
					uid   : getUrlParam('uid')   || getCookie('uid'),
					token : getUrlParam('token') || getCookie('token')
				}
				return userinfo
			},
			//验证店铺链接
			valiLink(){
				//店铺链接不存在
				if(!this.hasLink){
					return
				}
				if(this.onlineInfo){
					this.onlineInfo = {}
				}
				let info = {
					userinfo : this.getParams(),
					shop_url : this.onlineLink
				}
				this.$vux.loading.show({text:'店铺查询中'})
				this.$axiosGet('/api/maker/validateOnlineStore',{
					data : JSON.stringify(info)
				}).then( res => {
					this.$vux.loading.hide()
					if(res.code === 200){
						this.hasStore = false
						this.disable2 = true
						this.onlineInfo = res.data	
						this.onlineInfo.facepath = res.data.face_path
					}
					//失败的状态
					else if(res.code === 404 || res.code === 201){
						this.tipShow = true
						setTimeout( () => {
							this.tipShow = false
						},2000)
						this.tipTitle = res.data || '店铺不存在，请换个链接重试'
					}
				}).catch( err => {
					//25秒之后没响应，
					this.$vux.loading.hide()
					this.tipShow = true
						setTimeout( () => {
							this.tipShow = false
						},2000)
					this.tipTitle = '请求超时，请重新再试'
				})
			},
			//将图片转为base64
			changeBase64(img){
				var canvas = document.createElement("canvas");
			    canvas.width = img.width;
			    canvas.height = img.height;
			    var ctx = canvas.getContext("2d");
			    ctx.drawImage(img, 0, 0, img.width, img.height);
			    var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
			    var dataURL = canvas.toDataURL("image/"+ext);
			    return dataURL;
			},
			
			//点击下一步，获取服务器图片
			submitOnline(){
				//店铺链接验证不通过
				if(!this.disable2){
					return
				}
				if(this.hasStore){
					this.getOnlineInfo()
					return
				}
				this.$vux.loading.show({text:'正在创建'})
				var image = new Image();
					image.crossOrigin = '';
					image.src = this.onlineInfo.face_path;
					image.onload = () => {
					  //获取到base64					  
					  var base64 = this.changeBase64(image);
					  //上传base图片
					  this.$axiosPost('/utils/files/uploadbase64.json',{
					  		upload : base64
					  },true).then( res => {
					  		this.$vux.loading.hide()					  		
					  		//上传成功
					  		if(res.code === 200){
					  			this.onlineInfo.face_path = res.data.path		//相对地址的图片
					  			this.onlineInfo.facepath  = res.data.fullpath	//绝对地址的图片
					  			//执行提交
					  			this.getOnlineInfo()
					  		}
					  })
					}

			},
			//提交线上店铺信息
			getOnlineInfo(){				
				let info = Object.assign({userinfo : this.getParams()},this.onlineInfo)
				this.$axiosGet('/api/maker/createOnlineStore',{
					data : JSON.stringify(info)
				}).then( res => {
					this.$vux.loading.hide()
					//创建成功
					if(res.code === 200){
						this.dshow = true
					}
					//已经创建过
					else if(res.code === 403){
						this.hasStore = true
						this.tipShow = true
						setTimeout( () => {
							this.tipShow = false
						},2000)
						this.tipTitle = res.data || '该店铺已经被创建'
					}
					//开通失败
					else{
						this.tipShow = true
						setTimeout( () => {
							this.tipShow = false
						},2000)
						this.tipTitle = res.data || '开通失败'
					}
				})
			},
			//实体店铺是否已经存在
			hasStore(){
				//店铺名称不存在
				if(!this.entityName){
					return
				}
				let info = {
					userinfo : this.getParams(),
					name     : this.entityName
				}
				this.$vux.loading.show({text:'正在查询'})
				this.$axiosGet('/api/maker/isStoreExist',{
					data : JSON.stringify(info)
				}).then( res => {
					this.$vux.loading.hide()
					if(res.code === 200){						
						this.disable1 = true
					}else{
						this.tipShow = true
						setTimeout( () => {
							this.tipShow = false
						},2000)
						this.tipTitle = res.data || '店铺已经存在了，请换个名字吧'
					}
				})
			},
			//点击下一步，获取实体店的资料
			submitEntity(){
				//店铺验证不通过
				if(!this.disable1){
					return
				}
				//地址不能为空
				if(!this.address.length){
					this.$vux.toast.text('请选择所在地','top')
					return
				}
				//店铺名称不能为空
				if(!this.entityName){
					this.$vux.toast.text('请填写店铺名称','top')
					return
				}
				this.address.forEach( (item,index) => {
					if(item === "110019" || item === "120111" || item === "310111" || item === "500111"){
						this.address.splice(index,1)
					}				
				})
				let area = this.address.join(';')
				this.$router.push({path:'/proxyOpenShop',query:{area:area,name:this.entityName,branch:this.branchShop}})
			}
		},
		watch:{
			entityName(){
				if(!this.entityName){
					this.disable1 = false
				}
			},
			onlineLink(){
				if(this.onlineLink){
					this.hasLink = true
				}else{
					this.hasLink = false
				}
			}
		},
		computed: {
			newAddressData(){
				if(this.cityList.length){
					this.cityList.forEach(item=>{
					if(item.parent === "110000"){
						item.parent = "110019"
					}
					if(item.parent === "120000"){
						item.parent = "120111"
					}
					if(item.parent === "310000"){
						item.parent = "310111"
					}
					if(item.parent === "500000"){
						item.parent = "500111"
					}
					})
					this.cityList.push({
						name : "市辖区",
						parent : "110000",
						value  : "110019"
					})
					this.cityList.push({
						name : "市辖区",
						parent : "120000",
						value  : "120111"
					})
					this.cityList.push({
						name : "市辖区",
						parent : "310000",
						value  : "310111"
					})
					this.cityList.push({
						name : "市辖区",
						parent : "500000",
						value  : "500111"
					})	
					return this.cityList
				}
				return [{
					name : "",
					parent : "",
					value  : ""
				}]
			}
		},
		components: {
			XHeader,
			Tab,
			TabItem,
			Icon,
			XAddress,
			XButton,
			XDialog
		},

	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
	.create_shop /deep/ .vux-popup-picker-select{
		padding: 0 .21rem;
		height: .72rem;
		line-height: .72rem;
		border: none;
		background: #efefef;
	}
	.create_shop /deep/ .vux-tap-active{
		padding:0;
	}
	.create_shop /deep/ .weui-cell__ft{
		display: none;
	}
		.dialog-demo {
		  .weui-dialog{
		    border-radius: 8px;
		    padding-bottom: 8px;
		  }
		  .title{
		  	line-height: .8rem;
		  }
		  .dialog-title {
		    line-height: 30px;
		    color: #666;
		  }
		  .img-box {
		    overflow: hidden;
		  }
		  .vux-close {
		    margin-top: 8px;
		    margin-bottom: 8px;
		  }
		}
	.create_shop {
		min-height: 100%;
		background: #fff;
		padding-bottom: 2rem;
		.content {
			.tip{
				z-index: 999;
				position: fixed;
				top: 0;
				padding: 0 .2rem;
				display: flex;
				flex-direction: row;
				justify-content: inherit;
				height: 1.4rem;
				width: 100%;
				line-height: 1.9rem;
				text-align: left;
				color: #fff;
				font-size: .32rem;
				background: #f10c44;
			}
			.store_name {
				margin: 0 0 .66rem 0;
				padding: 0 .35rem;
				position: relative;
				>input {
					border: none;
					width: 100%;
					height: .75rem;
					line-height: .75rem;
					border-radius: .05rem;
					background: #efefef;
					font-size: .27rem;
					color: #000;
					padding: 0 .22rem;
					&::placeholder {
						font-size: .27rem;
						color: #8e8e8e;
					}
				}
				.clear {
					position: absolute;
					top: 50%;
					right: .6rem;
					transform: translateY(-50%);
				}
			}
			.sel_store_type {
				position: relative;
				padding: .48rem 0 0 0;
				>h3 {
					margin-top: .4rem;
					font-size: .38rem;
					color: #000;					
				}
				.back-icon{
					position: absolute;
					top: .9rem;
					left: .3rem;
					height: .6rem;
					width: .6rem;
					line-height: .6rem;
					text-align: center;
					background: rgba(0,0,0,.5);
					color: #fff;
					border-radius: 50%;
					font-size: .28rem;
				}
				.type_lists {
					display: flex;
					flex-wrap: wrap;
					margin: .5rem 0 .5rem 0;
					.type-warrp{
						flex: 1;
						padding: .2rem;
						height: 2.46rem;
						.type_list {
							margin: 0 auto;
							width: 2.06rem;														
							line-height: 2.06rem;
							border: 1px solid #161616;
							border-radius: 50%;
							font-size: .38rem;
							color: #000;						
							position: relative;						
							.success {
								width: .48rem;
								position: absolute;
								right: 0;
								top: 0;							
							}
						}
						.sel {
							border-color: #f4003f;
							color: #f4003f;
						}
					}


				}
			}
			.sel_area {
				overflow: hidden;
				padding: 0 .36rem;
				margin-bottom: .6rem;
				border-radius: .05rem;
				img {
					width: .2rem;
					height: .1rem;
					margin-right: .1rem;
				}
				.rotates {
					transform: rotate(180deg);
				}
				p {
					font-size: .28rem;
					color: #1a1a1a;
				}
				.area_lists {
					position: absolute;
					top: .65rem;
					left: 0rem;
					width: 100%;
					max-height: 5rem;
					overflow: auto;
					text-align: left;
					border: 1px solid #d1d1d1;
					background: #fff;
					z-index: 99;
					.area_list {
						font-size: .28rem;
						color: #1a1a1a;
						white-space: nowrap;
						padding: .15rem .4rem;
					}
					.sel {
						background: #f3f3f3;
						color: red;
					}
				}
			}
			.trade {
				margin: .86rem 0 0 0;
				>h2 {
					font-size: .38rem;
					color: #000;
					text-align: left;
					padding: 0 .28rem;
				}
				.trade_lists {
					display: flex;
					flex-wrap: wrap;
					padding: 0 .3rem 0 .17rem;
					.trade_list {
						background: #efefef;
						border: 1px solid #efefef;
						border-radius: .05rem;
						margin: .26rem 0 0 .13rem;
						padding: .24rem .3rem;
						font-size: .29rem;
						color: #000;
					}
					.sel {
						background: #fff;
						color: #f3013d;
						border-color: #f3013d;
					}
				}
			}
			>button {
				position: fixed;
				left: 50%;
				bottom: .82rem;
				transform: translateX(-50%);
				border: none;
				width: 3.1rem;
				height: .82rem;
				line-height: .82rem;
				border-radius: .05rem;
				background: #b4b4b4;
				font-size: .37rem;
				color: #fff;
				margin: .8rem 0 0 0;
			}
			.reds{
				background: #f4003e;
			}
		}
		.store_content2{
			.links{
				width: 90%;
				font-size: .22rem;
				color: #ea0641;
				text-align: right;
				margin: .32rem auto .82rem auto;
			}
			.btns{
				display: flex;
				justify-content: space-around;
				button{
					border: none;
					width: 2.48rem;
					height: .74rem;
					line-height: .74rem;					
					font-size: .28rem;
					border-radius: .05rem;					
				}
				button:nth-of-type(1){
					background: #fff;
					color: #f40045;
					border: 1px solid #f40045;
				}
				button:nth-of-type(2){
					background: #b4b4b4;
					color: #fff;
				}

			}
			.info{
				.avatar{
					height: 1.4rem;
					width: 1.4rem;
					margin: .1rem auto;
				}
				.title{
					color: #888;
				}
			}

		}
	}
</style>